<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="160px" class="demo-ruleForm" size="default"
      status-icon>
      <el-form-item label="字典名称">
        <el-select filterable clearable v-model="ruleForm.belongDictId" placeholder="请选择数据字典" @change="handleChangeDict">
          <el-option v-for="(item, index) in dictList" :key="index" :label="item.dictName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="表字段名" prop="tableFieldName">
        <el-input v-model="ruleForm.tableFieldName" @change="handleChangeTableFieldName" />
      </el-form-item>
      <el-form-item label="字段名" prop="fieldName">
        <el-input v-model="ruleForm.fieldName" />
      </el-form-item>
      <el-form-item label="字段长度" prop="charSize">
        <el-input-number v-model="ruleForm.charSize" :min="1" />
      </el-form-item>
      <el-form-item label="唯一字段">
        <el-input v-model="ruleForm.onlyFields" />
      </el-form-item>
      <el-form-item label="规则名称" prop="ruleId">
        <el-select filterable clearable v-model="ruleForm.ruleId" placeholder="请选择数据字典" @change="handleChangeRule">
          <el-option v-for="(item, index) in ruleList" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否审批" prop="isApproval">
        <el-radio-group v-model="ruleForm.isApproval">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否校验" prop="isCheck">
        <el-radio-group v-model="ruleForm.isCheck">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否主键" prop="isKey">
        <el-radio-group v-model="ruleForm.isKey">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否必填" prop="isNotNull">
        <el-radio-group v-model="ruleForm.isNotNull">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否参与过期提醒" prop="isExpireRemind">
        <el-radio-group v-model="ruleForm.isExpireRemind">
          <el-radio label="0">否</el-radio>
          <el-radio label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="版本号" prop="versionNumber">
        <el-input-number v-model="ruleForm.versionNumber" :min:="1" :max='3' />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import apiMod from '@/apiMod'
interface RuleForm {
  belongDictId: string
  belongDictName: string
  tableFieldName: string
  fieldName: string
  charSize: number
  onlyFields: string
  ruleId: string
  ruleName: string
  isApproval: string
  isCheck: string
  isKey: string
  isNotNull: string
  isExpireRemind: string
  versionNumber: number
  tableConfigId?: number
  tableName?: string
  id?: string
}
interface Props {
  tableConfigId: number
  tableName: string
  id?: string
}
const props = defineProps<Props>()
const dictList = ref([])
const ruleList = ref([])
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RuleForm>({
  belongDictId: '',
  belongDictName: '',
  tableFieldName: '',
  fieldName: '',
  charSize: 0,
  onlyFields: '',
  ruleId: '',
  ruleName: '',
  isApproval: '0',
  isCheck: '0',
  isKey: '0',
  isNotNull: '0',
  isExpireRemind: '0',
  versionNumber: 1
})
const emit = defineEmits<{
  (e: 'updateTable')
}>()

const rules = reactive<any>({
  tableFieldName: [
    { required: true, message: '请输入表字段名', trigger: 'blur' },
  ],
  fieldName: [
    { required: true, message: '请输入字段名', trigger: 'blur' },
  ],
  isApproval: [
    { required: true, message: '请选择是否审批', trigger: 'change' },
  ],
  isCheck: [
    { required: true, message: '请选择是否校验', trigger: 'change' },
  ],
  isKey: [
    { required: true, message: '请选择是否主键', trigger: 'change' },
  ],
  isNotNull: [
    { required: true, message: '请选择是否必填', trigger: 'change' },
  ]
})
onMounted(() => {
  getDictList()
  getRuleList()

  if (props.id || props.id == '0') {
    getDetail()
  }
})
const getDictList = async () => {
  const params = {
    pageParaPO: {
      current: 1,
      size: 100000
    }
  }
  const res = await apiMod.sys_dict_page(params)
  if (res.code == 0) {
    dictList.value = res.data.records
  }
}
const handleChangeDict = (data) => {
  ruleForm.value.belongDictName = dictList.value.filter(item => item.id == data)[0].dictName
}
const getDetail = async () => {
  const res = await apiMod.view_metadata_view(props.id)
  console.log('编辑时的数据', res)
  if (res.code == 0) {
    res.data.isApproval = res.data.isApproval ? '1' : '0'
    res.data.isCheck = res.data.isCheck ? '1' : '0'
    res.data.isNotNull = res.data.isNotNull ? '1' : '0'
    res.data.isKey = res.data.isKey ? '1' : '0'
    res.data.isExpireRemind = res.data.isExpireRemind ? '1' : '0'
    ruleForm.value = res.data
  }
}
const handleChangeTableFieldName = async (data) => {
  if (!data) {
    return
  }
  const params = {
    tableConfigId: props.tableConfigId,
    tableName: props.tableName,
    columnName: data,
  }
  const res = await apiMod.view_metadata_tableColumnList(params)
  console.log('所有数据', res)
  if (res.code == 0) {
    const fieldInfo = res.data[0]
    if (!Number(ruleForm.value.fieldName)) {
      ruleForm.value.fieldName = fieldInfo.label
    }
    if (!Number(ruleForm.value.charSize)) {
      ruleForm.value.charSize = fieldInfo.column_length
    }
    if (!Number(ruleForm.value.isKey)) {
      // ruleForm.value.isKey
      ruleForm.value.isKey = fieldInfo.key_flag
    }
    if (!Number(ruleForm.value.isNotNull)) {
      ruleForm.value.isNotNull = fieldInfo.require_flag
    }
  }
}
const getRuleList = async () => {
  const res = await apiMod.getDictItemList(['METADATA_RULE'])
  ruleList.value = res.data.METADATA_RULE
}
const handleChangeRule = (data) => {
  ruleForm.value.ruleName = ruleList.value.filter(item => item.value == data)[0].label
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.value.tableConfigId = props.tableConfigId
      ruleForm.value.tableName = props.tableName
      let res
      if (props.id) {
        ruleForm.value.id = props.id
        res = await apiMod.view_metadata_edit(ruleForm.value)
      } else {
        res = await apiMod.view_metadata_add(ruleForm.value)
      }
      if (res.code == 0) {
        if (res.msg) {
          ElMessage.success(res.msg)
        } else {
          if (props.id) {
            ElMessage.success('编辑成功')
          } else {
            ElMessage.success('添加成功')
          }

        }

        emit('updateTable')
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<style scoped></style>